package src;

/**
 * 循环队列
 */
public class LoopQueue<E> implements Queue<E> {

    private E[] data;
    private int front, tail;
    private int size;

    public LoopQueue(int capacity){
        data = (E[]) new Object[capacity + 1];
        size = front = tail = 0;
    }
    public LoopQueue(){
        this(10);
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public void enQueue(E e) {
        // 先判断是否是满的
        if ( (tail + 1) % data.length == front) {
            resize(getCapacity() * 2); // 队列扩容
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size ++;
    }

    @Override
    public E deQueue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("cannot dequeue form a empty queue");
        }
        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size --;
        // 容积缩小
        if (size <= (getCapacity() / 4) && (getCapacity() / 2) != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        return data[front];
    }

    private void resize(int len){
        E[] newData = (E[]) new Object[len + 1];
        for (int i = 0; i < size; i++) {
            // 复制旧数据
            newData[i] = data[(front + i) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    public int getCapacity(){
        return data.length - 1;
    }

    @Override
    public String toString() {
        StringBuffer res = new StringBuffer();
        res.append("Queue: <--");
        res.append("[");
        for (int i = 0; i < size; i++) {
            res.append(data[(front + i) % data.length]);
            if (i != size - 1){
                res.append(", ");
            }
        }
        res.append("]");
        res.append(String.format("(%d/%d)", size, getCapacity()));
        res.append("<--");
        return res.toString();
    }
}